# -*- encoding: utf-8 -*-

"""
@File:      tc_libmnl_libmnl_func_005.py
@Time:      2024/03/29 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libmnl_libmnl_func_005.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libmnl libmnl-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >libmnl_test5.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <libmnl/libmnl.h>

#define NUM_THREADS 5

void *thread_function(void *arg) {
    struct mnl_socket *nl;
    nl = mnl_socket_open(NETLINK_GENERIC);

    if (nl == NULL) {
        perror("mnl_socket_open");
        return NULL;
    }

    if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
        perror("mnl_socket_bind");
        mnl_socket_close(nl);
        return NULL;
    }

    printf("Thread ID: %ld, Netlink socket opened and bound successfully\\n", pthread_self());

    mnl_socket_close(nl);
    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    int i, rc;

    for (i = 0; i < NUM_THREADS; i++) {
        rc = pthread_create(&threads[i], NULL, thread_function, NULL);

        if (rc) {
            fprintf(stderr, "Error: unable to create thread, %d\\n", rc);
            exit(-1);
        }
    }

    for (i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("All threads completed successfully\\n");

    return 0;
}
EOF'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o libmnl_test5 libmnl_test5.c -lmnl -lpthread")
        code, libmnl_result = self.cmd("./libmnl_test5")
        self.assertIn("All threads completed successfully", libmnl_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf libmnl_test5.c libmnl_test5")
